<template>
  <div>
    <el-upload
      class="upload-demo"
      ref="upload"
      :action="uploadUrl"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :auto-upload="false"
      :on-success="onSuccess"
      :on-error="onError"
    >
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <el-button
        style="margin-left: 10px"
        size="small"
        type="success"
        @click="submitUpload"
        >上传到服务器</el-button
      >
      <div slot="tip" class="el-upload__tip">
        只能上传jpg/png文件，且不超过500kb
      </div>
    </el-upload>
  </div>
</template>

<script>
import { uploadUrl } from "@/api/index";
export default {
  data() {
    return {
      fileList: [],
      uploadUrl: uploadUrl,
    };
  },
  methods: {
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      //   console.log(file, fileList);
    },
    handlePreview(file) {
      //   console.log(file);
    },
    onSuccess(response, file, fileList) {
      // response.url：upload/1673964733945-4d4a6880b6b36807d6c328888ef8854c.jpg
      // 上传成功访问图片路径 http://127.0.0.1:7878/服务器图片地址（不要/upload，需要对路径进行截取）
      let url = "http://127.0.0.1:7878/" + response.url.slice(7);
      this.$emit("sendImgUrl", url);
      this.$message({
        type: "success",
        message: "图片上传成功",
      });
    },
    onError(err, file, fileList) {
      this.$message({
        type: "error",
        message: "图片上传失败",
      });
    }
  },
};
</script>

<style lang="less" scoped></style>
